<template>
  <el-dialog
    title="系统公告"
    :visible.sync="visible"
    width="80vh"
    :show-close="false"
    height="90vh"
  >
    <div v-html="noticeInfo.noticeContent" style="margin-left:10px;margin-right:10px" class="ql-editor"></div>
    <span slot="footer" class="dialog-footer">
      <el-checkbox v-model="notShowAgain" style="margin-right: 10px;">不再显示</el-checkbox>
      <el-button type="primary" @click="confirm" :disabled="isCountingDown" :class="{ 'active-button': !isCountingDown }">{{ buttonText }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPublishedNotice } from "@/api/system/notice"
import { parseTime } from "@/utils/basic";

export default {
  data() {
    return {
      visible: false,
      notShowAgain: false,
      noticeInfo: {},
      isCountingDown: true, // 是否在倒计时
      countdown: 5, // 倒计时秒数
      buttonText: '倒计时 5 秒', // 按钮文本
      timer: null // 定时器
    }
  },
  methods: {
    confirm() {
      if (this.notShowAgain) {
        localStorage.setItem('hideAnnouncement', 'true');
      }
      this.visible = false;
    },
    // 显示公告（外部调用）
    async show() {
      const notice = await this.getPublishedNotice();
      if (!notice) {
        localStorage.removeItem('hideAnnouncement');
        return;
      }

      const isNoticeValid = this.checkNoticeValidity(notice);
      if (isNoticeValid) {
        this.noticeInfo = notice;
        this.visible = !localStorage.getItem('hideAnnouncement');
        this.startCountdown();
      } else {
        localStorage.removeItem('hideAnnouncement');
      }
    },
    // 检查公告是否在有效期内
    checkNoticeValidity(notice) {
      const currentDate = new Date(parseTime(Date.now(), '{y}-{m}-{d}'));
      return currentDate >= new Date(notice.validFrom) && currentDate <= new Date(notice.validTo);
    },
    // 查询是否存在发布的公告
    async getPublishedNotice() {
      const res = await getPublishedNotice();
      return res.data || null;
    },
    // 启动倒计时
    startCountdown() {
      this.timer = setInterval(() => {
        this.countdown--;
        this.buttonText = `倒计时 ${this.countdown} 秒`;
        if (this.countdown <= 0) {
          clearInterval(this.timer);
          this.isCountingDown = false;
          this.buttonText = '我已阅读，并知晓该公告';
        }
      }, 1000);
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
}
</script>

<style scoped>
/deep/ .ql-editor img {
  max-width: 50%;
  height: 50%;
}
/deep/ .ql-editor {
  overflow: auto;
}
.active-button {
  background-color: #409EFF;
  border-color: #409EFF;
}
</style>
